const http = require('http');
const axios = require('axios');
const cheerio = require('cheerio');

const port = 8081;

const server = http.createServer(async (req, res) => {
  try {
    // 使用猫眼API获取电影数据
    const apiUrl = 'https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?limit=15';
    const { data } = await axios.get(apiUrl, {
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
        'Referer': 'https://maoyan.com/',
        'X-Requested-With': 'XMLHttpRequest'
      },
      timeout: 10000
    });

    if (!data || !data.data || !data.data.hot) {
      throw new Error('API返回数据格式不正确');
    }

    const movies = data.data.hot.map((item, index) => ({
      id: item.id || index,
      name: item.nm || '未知电影',
      score: item.sc || '暂无评分'
    }));

    console.log('从API获取的电影数据:', movies);

    // 生成HTML响应
    res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
    const htmlContent = "<!DOCTYPE html>" +
      "<html>" +
      "<head>" +
        "<meta charset=\"UTF-8\">" +
        "<title>猫眼电影数据</title>" +
        "<style>" +
          "body { font-family: \"Microsoft YaHei\", sans-serif; padding: 20px; }" +
          "h1 { text-align: center; margin-bottom: 30px; }" +
          ".movie-container { display: flex; gap: 20px; margin-top: 30px; }" +
          ".movie-column { flex: 1; border: 1px solid #ddd; padding: 15px; border-radius: 5px; }" +
          ".movie-title { font-weight: bold; text-align: center; margin-bottom: 15px; font-size: 18px; }" +
          ".movie-item { padding: 8px 0; border-bottom: 1px solid #eee; }" +
        "</style>" +
      "</head>" +
      "<body>" +
        "<h1>猫眼电影数据</h1>" +
        "<div class=\"movie-container\">" +
          "<div class=\"movie-column\">" +
            "<div class=\"movie-title\">电影ID</div>" +
            movies.map(m => "<div class=\"movie-item\">" + m.id + "</div>").join('') +
          "</div>" +
          "<div class=\"movie-column\">" +
            "<div class=\"movie-title\">电影名称</div>" +
            movies.map(m => "<div class=\"movie-item\">" + m.name + "</div>").join('') +
          "</div>" +
          "<div class=\"movie-column\">" +
            "<div class=\"movie-title\">电影评分</div>" +
            movies.map(m => "<div class=\"movie-item\">" + m.score + "</div>").join('') +
          "</div>" +
        "</div>" +
      "</body>" +
      "</html>";
    
    res.end(htmlContent);
  } catch (err) {
    res.writeHead(500);
    res.end('爬取失败: ' + err.message);
    console.error('爬取失败:', err);
  }
});

server.listen(port, () => {
  console.log(`爬虫服务运行在 http://localhost:${port}`);
});